/*
 * Creation : 22/03/2013
 */
package a2012c2.t6.chat.client;

import java.io.IOException;
import java.util.Collection;
import java.util.InvalidPropertiesFormatException;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Properties;
import java.util.TreeMap;

/**
 * Fabrica que se encarga de buscar un icono y devolver el codigo html de la
 * imagen
 * 
 * @author mBrizi
 * 
 */
public final class IconFactory {

	private static IconFactory instance;

	private static Map<String, Icon> myIcons;

	private static Properties iconsProperties = new Properties();

	private IconFactory() {
		try {
			iconsProperties.loadFromXML(this.getClass().getResourceAsStream("/properties/properties.xml"));
			myIcons = new TreeMap<String, Icon>();
			for (Entry<Object, Object> property : iconsProperties.entrySet()) {
				String path = this.getClass().getResource((String) property.getValue()).getPath();
				myIcons.put((String) property.getKey(), new Icon((String) property.getKey(), path));
			}
		} catch (InvalidPropertiesFormatException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	/**
	 * @return instance
	 * @throws InvalidPropertiesFormatException
	 * @throws IOException
	 */
	public static final IconFactory getInsatance() {
		if (instance == null) {
			instance = new IconFactory();
		}
		return instance;
	}

	/**
	 * @return
	 */
	public Collection<Icon> getIcons() {
		return myIcons.values();
	}

	/**
	 * @return
	 */
	public Icon getDefaultIcon() {
		return getIcon(":)");
	}

	/**
	 * @param path
	 * @return
	 */
	public Icon getIcon(String key) {
		return myIcons.get(key);
	}
	/**
	 * @param posibleIcon
	 * @return el codigo html de la imagen
	 * @throws MalformedURLException
	 */
	public String getIconToHtml(String posibleIcon) {
		String html = posibleIcon;

		if (myIcons.containsKey(posibleIcon)) {

			Icon icon = myIcons.get(posibleIcon);

			// String width = myIcons.getProperty("width");
			// String height = myIcons.getProperty("height");
			String width = "25";
			String height = "25";
			String style = "width='" + width + "' height='" + height + "'";
			String path = this.getClass().getResource(iconsProperties.getProperty(icon.getKey())).toString();
			String iconHtml = "<img src=\"" + path + "\" " + style + "/>";

			html = iconHtml;
		}
		return html;
	}
}
